package com.gxpt.app.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.normal;
import com.gxpt.app.bean.upload_bean;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.utils.v24.v_2_4;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_life_need_add)
public class Activity_life_need_add extends BaseActivity {

    private final int SDK_PERMISSION_REQUEST = 127;

    private static final int NONE                 = 0;
    private static final int PHOTO_GRAPH          = 1;// 拍照
    private static final int PHOTO_ZOOM           = 2; // 缩放
    private static final int PHOTO_RESOULT        = 3;// 结果
    private static final String IMAGE_UNSPECIFIED = "image/*";

    String tmppicPath    = "";
    String cropedpicPath = "";

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.toIndusSel)
    RelativeLayout toIndusSel;

    @ViewInject(R.id.toZhaobiaoModel)
    RelativeLayout toZhaobiaoModel;


    @ViewInject(R.id.toAreaSel)
    RelativeLayout toAreaSel;

    @ViewInject(R.id.put_3)
    TextView put_3;

    @ViewInject(R.id.toShenfen)
    RelativeLayout toShenfen;

    @ViewInject(R.id.put_5)
    TextView put_5;

    @ViewInject(R.id.toPicSel)
    LinearLayout toPicSel;

    @ViewInject(R.id.put_1)
    TextView put_1;

    @ViewInject(R.id.put_8)
    TextView put_8;


    @ViewInject(R.id.img_view)
    ImageView img_view;


    @ViewInject(R.id.txt_pic)
    TextView txt_pic;


    @ViewInject(R.id.put_2)
    EditText put_2;

    @ViewInject(R.id.put_4)
    EditText put_4;

    @ViewInject(R.id.put_6)
    EditText put_6;

    @ViewInject(R.id.put_7)
    EditText put_7;

    @ViewInject(R.id.put_9)
    EditText put_9;

    @ViewInject(R.id.put_10)
    EditText put_10;

    @ViewInject(R.id.toSure)
    Button toSure;


    String industry_id;
    String industry_subid;

    String province_id;
    String city_id;

    String bidding_model;//交易模式 0一口价1招标
    String identity;//0需求方1中间商

    String pic_path="";

    //临时变量
    Uri photoURI;//相加拍摄保存路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);
        initView();

        tmppicPath    = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+Constant.PRO_DIR+"/"+ Constant.UPLOAD_PIC_TEMP_NAME;
        cropedpicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+Constant.PRO_DIR+"/"+Constant.UPLOAD_PIC_CROP_NAME;

//        Logger.i(" tmppicPath= "+tmppicPath);
        getPersimmions();

    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 相机
            if(checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.CAMERA);
            }
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }


            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        if(messageEvent.getMessageType()==Constant.ACTION_indus_sel){
            put_1.setText(messageEvent.getMessage());
            industry_id    = messageEvent.getId1();
            industry_subid = messageEvent.getId2();
        }else if(messageEvent.getMessageType()==Constant.ACTION_city_sel){
            put_8.setText(messageEvent.getMessage());
            province_id    = messageEvent.getId1();
            city_id        = messageEvent.getId2();
        }else if(messageEvent.getMessageType()==Constant.ACTION_pay_success){
            closeActivity();
        }
    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_need));
    }


    @Override
    public void initData() {

    }



    @Event(value={R.id.toback,R.id.toZhaobiaoModel,R.id.toShenfen,R.id.toPicSel,R.id.toIndusSel,R.id.toAreaSel,R.id.toSure})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toIndusSel:
                jumpActivity(Activity_indus_select.class,false);
                break;
            case R.id.toZhaobiaoModel:
                Dialog_zhaobiaomodel();
                break;
            case R.id.toShenfen:
                Dialog_shenfen();
                break;
            case R.id.toPicSel:
                Dialog_picsel();
                break;
            case R.id.toAreaSel:
                Bundle b = new Bundle();
                b.putString("FORM_","Activity_life_need_add");
                jumpActivity(Activity_city_select_2.class,b,false);
                break;
            case R.id.toSure:
                if(checkData()){
                    //
//                    toNet_pubdemand();
                    Bundle bundle = new Bundle();
                    bundle.putString("put_1",put_1.getText().toString());
                    bundle.putString("put_2",put_2.getText().toString());
                    bundle.putString("put_3",put_3.getText().toString());
                    bundle.putString("put_4",put_4.getText().toString());
                    bundle.putString("put_5",put_5.getText().toString());
                    bundle.putString("put_6",put_6.getText().toString());
                    bundle.putString("put_7",put_7.getText().toString());
                    bundle.putString("put_8",put_8.getText().toString());
                    bundle.putString("put_9",put_9.getText().toString());
                    bundle.putString("put_10",put_10.getText().toString());

                    bundle.putString("industry_id",industry_id);
                    bundle.putString("industry_subid",industry_subid);
                    bundle.putString("province_id",province_id);
                    bundle.putString("city_id",city_id);
                    bundle.putString("bidding_model",bidding_model);
                    bundle.putString("identity",identity);
                    bundle.putString("pic_path",pic_path);

                    jumpActivity(Activity_life_need_confirm.class,bundle,false);

                }
                break;
        }
    }

    private boolean checkData(){
        if(put_1.getText().toString().isEmpty() ||
                put_2.getText().toString().isEmpty() ||
                put_3.getText().toString().isEmpty() ||
                put_4.getText().toString().isEmpty() ||
                put_5.getText().toString().isEmpty() ||
                put_6.getText().toString().isEmpty() ||
                put_7.getText().toString().isEmpty() ||
                put_8.getText().toString().isEmpty() ||
                put_9.getText().toString().isEmpty() ||
                put_10.getText().toString().isEmpty()||
                industry_id.isEmpty()||
                industry_subid.isEmpty()){
            T.show(context, getResources().getString(R.string.alert_putisnotnull), 0);
            return false;
        }
        return true;
    }


    public void Dialog_zhaobiaomodel(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_zhaobiaomodel, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                put_3.setText(getResources().getString(R.string.txt_yikoujia));
                bidding_model = "0";
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                put_3.setText(getResources().getString(R.string.txt_zhaobiao));
                bidding_model = "1";
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    public void Dialog_shenfen(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_shenfen, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                put_5.setText(getResources().getString(R.string.txt_xuqiufang));
                identity = "0";
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                put_5.setText(getResources().getString(R.string.txt_zhongjianshang));
                identity = "1";
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    public void Dialog_picsel(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_pic_sel, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckPerission_CAMERA();
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, PHOTO_ZOOM);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTO_GRAPH) {
            startPhotoZoom(photoURI);
        }

        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTO_ZOOM) {
            startPhotoZoom(data.getData());
        }

        // 处理结果
        if (requestCode == PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                saveCropedPhoto(photo);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    ////////////////////////////////////////////////////////////////////////////////////剪裁图片
    /**
     * 收缩图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
//        intent.putExtra("crop", "false");//进行修剪

        intent.putExtra("crop", "true");

        intent.putExtra("scale", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 5);
        intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY",270);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    ////////////////////////////////////////////////////////////////////////////////////保存剪裁后的图片
    private void saveCropedPhoto(Bitmap bmp){
        try{
//            String cropedpicPath = this.cropedpicPath;
            File fImage = new File(this.cropedpicPath);

            Logger.i(" == "+cropedpicPath);

            fImage.createNewFile();
            FileOutputStream iStream = new FileOutputStream(fImage);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, iStream);
            iStream.close();
            iStream =null;
            fImage =null;
            toNet_pic();

        }catch (Exception e){
            Logger.i("error...");
            e.printStackTrace();
        }

    }






    /**
     * 检测权限
     */
    private void CheckPerission_CAMERA() {

        Logger.i("当前版本号："+Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            Logger.i("showCameraAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(Activity_life_need_add.this,new String[]{Manifest.permission.CAMERA},Constant.REQUEST_TAKE_CAMERA_PERMISSION);
                return;
            }else{
                CheckPerission_STORAGE();
            }
        }else{
            CheckPerission_STORAGE();
        }
    }

    /**
     * 检测权限
     */
    private void CheckPerission_STORAGE() {
        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            Logger.i("writeSTORAGEAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(Activity_life_need_add.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},Constant.REQUEST_TAKE_STORAGE_PERMISSION);
                return;
            }else{
                createPhoto_path();
            }
        }else{
            createPhoto_path();
        }
    }







    private Uri contentUri;
    private File newFile;
    //拍照的代码
    private void createPhoto_path() {
//        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//
//        File imagePath = new File(Environment.getExternalStorageDirectory(), "images");
//        if (!imagePath.exists()) imagePath.mkdirs();
//        newFile = new File(imagePath, "default_image.jpg");
//
//        //第二参数是在manifest.xml定义 provider的authorities属性
//        contentUri = FileProvider.getUriForFile(this, "com.example.android.fileprovider", newFile);




//        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
//        photoURI = getOutputMediaFileUri();
//        imagePath = photoURI.getPath().substring(15);
//        i.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//        startActivityForResult(i, PHOTO_GRAPH);





        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
//                Logger.e("Build.VERSION.SDK_INT >= Build.VERSION_CODES.N");
                photoURI = v_2_4.get24MediaFileUri(context);



            } else {
//                Logger.e("7.0以下使用这种方式创建一个Uri");
                photoURI = v_2_4.getMediaFileUri(context);

            }
            Logger.e("photoURI.getPath() = "+photoURI.getPath());
            //将Uri传递给系统相机
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, PHOTO_GRAPH);
        }
    }


//    private Uri getUriForFile(File file) {
//        if (context == null || file == null) {
//            throw new NullPointerException();
//        }
//        Uri uri;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            uri = FileProvider
//                    .getUriForFile(context.getApplicationContext(), "com.example.android.fileprovider", file);
//        } else {
//            uri = Uri.fromFile(file);
//        }
//        return uri;
//    }

//    private Uri getOutputMediaFileUri() {
////        return Uri.fromFile(getOutputMediaFile());
//        return getUriForFile(this.context,getOutputMediaFile());
//    }

    ////////////////////////////////////////////////////////////////////////////////////NET_PIC
    public void toNet_pic() {
        hud.show();
        Logger.i("cropedpicPath=="+cropedpicPath);
        File file = new File(this.cropedpicPath);
        if (!file.exists())
        {
            T.show(context, "文件不存在，请修改文件路径", 1);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", ""+1);
        Map<String, String> headers = new HashMap<>();

        OkHttpUtils
                .post()
                .addFile("upfile", ""+Constant.UPLOAD_PIC_CROP_NAME, file)//
                .url(Constant.URL_upload_file)//
                .params(params)//
                .headers(headers)//
                .build()//
                .execute(pic_do);
    }
    StringCallback pic_do = new StringCallback(){
        @Override
        public void onError(Call call, Exception e, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                upload_bean data = new Gson().fromJson(s, upload_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    //do
                    pic_path = data.data;
                    PicassoUtils.Picasso_displayImage(context,Constant.IP+pic_path,img_view);
                    img_view.setVisibility(View.VISIBLE);
                    txt_pic.setVisibility(View.GONE);
                    T.show(context,""+getResources().getString(R.string.alert_success_do),0);

                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };






    //////NET DO
    StringCallback do_pubdemand = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    T.show(context,getResources().getString(R.string.alert_success_do),1);
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

//    /////NET
    private void toNet_pubdemand(){
        hud.show();
          JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "demand");
            jsonBody.put("serviceName",          "pubdemand");

            jsonBody.put("member_id",            AppUtils.get_user_id(context));
            jsonBody.put("industry_id",          industry_id);
            jsonBody.put("industry_subid",       industry_subid);
            jsonBody.put("title",                put_2.getText().toString());
            jsonBody.put("bidding_model",        bidding_model);
            jsonBody.put("project_amount",       put_4.getText().toString());
            jsonBody.put("identity",             identity);
            jsonBody.put("keywords",             put_6.getText().toString());

            jsonBody.put("telphone",             put_7.getText().toString());
            jsonBody.put("province_id",          province_id);
            jsonBody.put("city_id",              city_id);
            jsonBody.put("address",              put_9.getText().toString());
            jsonBody.put("description",          put_10.getText().toString());
            jsonBody.put("file_url",             pic_path);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i(jsonBody.toString()+" ==["+Constant.URL_pubdemand+" ]");
        HttpUtils.http_post_string(Constant.URL_pubdemand,jsonBody.toString(),do_pubdemand);
    }






}
